package cn.com.cis.web.actions;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.SAXException;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cn.com.cis.domain.Connection;
import cn.com.cis.domain.Database;
import cn.com.cis.domain.JobLog;
import cn.com.cis.domain.TreeEntity;
import cn.com.cis.domain.XmlJob;
import cn.com.cis.plugins.mybatis.PageInfo;
import cn.com.cis.service.ConnectionService;
import cn.com.cis.service.DataBaseService;
import cn.com.cis.service.ETLExecutorService;
import cn.com.cis.service.GenerateXmlService;
import cn.com.cis.service.JobLogService;
import cn.com.cis.service.TreeService;
import cn.com.cis.service.XmlJobService;

@Controller
@RequestMapping(value = "/EtlXml")
public class EtlXmlController {
	@Autowired
	private TreeService treeService;

	@Autowired
	private DataBaseService dataBaseService;
	
	@Autowired
	private XmlJobService xmlJobService;
	
	@Autowired
	private ConnectionService connectionService;

	private void setNavigateBar(ModelAndView mv) {
		mv.addObject("icon", "icon-list");
		mv.addObject("title", "ExtXml管理");
	}

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(@RequestParam(value = "page", defaultValue = "1", required = false) int page,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize) {
		ModelAndView mav = new ModelAndView("EtlXml/list3");
		setNavigateBar(mav);

		List<XmlJob> jobs = xmlJobService.selectJobsAndTemps(page, pageSize);
		PageInfo<XmlJob> pageInfo = new PageInfo<XmlJob>(jobs, pageSize);
		
		mav.addObject("page",page);
		mav.addObject("jobs", jobs);
		mav.addObject("pageInfo", pageInfo);

		return mav;
	}
	
	@RequiresPermissions("ExtXml管理:创建xml作业")
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView add() {
		ModelAndView mav = new ModelAndView("EtlXml/add");
		setNavigateBar(mav);
		
		List<Connection> connections = connectionService.selectAllConnections(0, 0);
		mav.addObject("connections", connections);
		
		return mav;
	}
	
	@RequiresPermissions("ExtXml管理:创建xml作业模板")
	@RequestMapping(value = "/addTemplate", method = RequestMethod.GET)
	public ModelAndView addTemplate() {
		ModelAndView mav = new ModelAndView("EtlXml/addTemplate");
		setNavigateBar(mav);
		
		return mav;
	}

	@RequiresPermissions("ExtXml管理:创建xml作业")
	@RequestMapping(value = "/AddNodeAjax", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String AddNodeAjax(String ajaxparam) {
		System.out.println(ajaxparam);
		try {
			String[] ajaxparamArray = ajaxparam.split("\\|");
			int nodeid = Integer.parseInt(ajaxparamArray[0]);
			int pid = Integer.parseInt(ajaxparamArray[1]);
			String nodename = ajaxparamArray[2];
			String mytreetype = ajaxparamArray[3];
			String jobid = ajaxparamArray[4];
			TreeEntity tree = new TreeEntity();
			tree.setId(nodeid);
			tree.setXmlid("test");
			tree.setPid(pid);
			tree.setName(nodename);
			tree.setMytreetype(mytreetype);
			if (jobid != null && jobid != "") {
				tree.setJobid(Integer.parseInt(jobid));
			}
			treeService.insertTree(tree);
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@Autowired
	ETLExecutorService etlExecutorService;

	@Autowired
	JobLogService js;

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/getJobStatus", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String getJobStatus(Integer logId) {
		JobLog log = js.selectJobEntityLogById(logId);

		return new Gson().toJson(log);
	}

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/GetNodeInfoAjax", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String GetNodeInfoAjax(String ajaxparam) {
		System.out.println(ajaxparam);
		try {
			String[] ajaxparamArray = ajaxparam.split("\\|");
			int nodeid = Integer.parseInt(ajaxparamArray[0]);
			int pid = Integer.parseInt(ajaxparamArray[1]);
			String nodename = ajaxparamArray[2];
			String mytreetype = ajaxparamArray[3];
			TreeEntity tree = new TreeEntity();
			tree.setId(nodeid);
			tree.setPid(pid);
			tree.setName(nodename);
			tree.setMytreetype(mytreetype);
			treeService.insertTree(tree);
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequiresPermissions("ExtXml管理:创建xml作业")
	@RequestMapping(value = "/SaveNodeInfoAjax", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public String SaveNodeInfoAjax(String nodeTreeType, String content, String connectionid, String nodeid) {
		try {
			TreeEntity tree = new TreeEntity();
			tree.setId(Integer.parseInt(nodeid));
			//System.out.println(nodeTreeType);
			//System.out.println(nodeTreeType.equals("val"));

			if (nodeTreeType.equals("properties")) {
				tree.setNodecontent(content);
				treeService.saveNodeContent(tree);
			} else if (nodeTreeType.equals("connection")) {
				String[] connectionList = content.split("\\|");
				tree.setConnectionid(connectionList[0]);
				tree.setName(connectionList[0]);
				tree.setNodecontent(connectionList[1]);
				treeService.saveConnectID(tree);
			} else if (nodeTreeType.equals("query") || nodeTreeType.equals("script")) {
				tree.setNodecontent(content);
				tree.setConnectionid(connectionid);
				treeService.saveNodeContent(tree);
			}
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/GetTreeNodesAllAjax", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String GetTreeNodesAllAjax() throws UnsupportedEncodingException {
		TreeEntity treeRoot = new TreeEntity();
		treeRoot.setId(1);
		treeRoot.setPid(0);
		treeRoot.setName(" ");
		treeRoot.setMytreetype("RootNode");
		List<TreeEntity> listTreeEntity = treeService.selectAllTree();
		//
		//把任务、preprity、connection节点集合放到集合的最前面
		List<TreeEntity> createjobList = new ArrayList<TreeEntity>();
		List<TreeEntity> updatejobList = new ArrayList<TreeEntity>();
		List<TreeEntity> preList = new ArrayList<TreeEntity>();
		List<TreeEntity> connList = new ArrayList<TreeEntity>();

		listTreeEntity.add(treeRoot);
		for (TreeEntity TreeTemp : listTreeEntity) {
			if (TreeTemp.getMytreetype().equals("layer")) {
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/layer.png");
			} else if (TreeTemp.getMytreetype().equals("createjob")) {
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/job.png");
				createjobList.add(TreeTemp);
				//listTreeEntity.remove(TreeTemp);
			} else if (TreeTemp.getMytreetype().equals("updatejob")) {
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/update.png");
				updatejobList.add(TreeTemp);
				//listTreeEntity.remove(TreeTemp);
			} else if (TreeTemp.getMytreetype().equals("properties")) {

				if (TreeTemp.getNodecontent() != null && TreeTemp.getNodecontent() != "") {
					String temptNodecontent = java.net.URLDecoder.decode(TreeTemp.getNodecontent(), "UTF-8");
					//替换大小于号
					/*
                    temptNodecontent = temptNodecontent.replace("<","&lt;");
                    temptNodecontent = temptNodecontent.replace(">", "&gt;");
                    temptNodecontent = temptNodecontent.replace("&lt;!--","<!--");
                    temptNodecontent = temptNodecontent.replace("--&gt;","-->");*/
					TreeTemp.setNodecontent(temptNodecontent);
				}

				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/properties.png");
				preList.add(TreeTemp);
				//listTreeEntity.remove(TreeTemp);
			} else if (TreeTemp.getMytreetype().equals("connection")) {
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/connection.png");
				String temptNodecontent = java.net.URLDecoder.decode(TreeTemp.getNodecontent(), "UTF-8");
				TreeTemp.setNodecontent(temptNodecontent);
				connList.add(TreeTemp);
				//listTreeEntity.remove(TreeTemp);
			} else if (TreeTemp.getMytreetype().equals("query")) {
				if (TreeTemp.getNodecontent() != null && TreeTemp.getNodecontent() != "") {
					String temptNodecontent = java.net.URLDecoder.decode(TreeTemp.getNodecontent(), "UTF-8");
					//替换大小于号
					temptNodecontent = temptNodecontent.replace("<", "&lt;");
					temptNodecontent = temptNodecontent.replace(">", "&gt;");
					temptNodecontent = temptNodecontent.replace("&lt;!--", "<!--");
					temptNodecontent = temptNodecontent.replace("--&gt;", "-->");
					TreeTemp.setNodecontent(temptNodecontent);
				}
				if (TreeTemp.getComment() != null && TreeTemp.getComment() != "") {
					String tempComment = java.net.URLDecoder.decode(TreeTemp.getComment(), "UTF-8");
					//替换大小于号
					tempComment = tempComment.replace("<", "&lt;");
					tempComment = tempComment.replace(">", "&gt;");
					tempComment = tempComment.replace("&lt;!--", "<!--");
					tempComment = tempComment.replace("--&gt;", "-->");
					TreeTemp.setComment(tempComment);
				}
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/query.png");
			} else if (TreeTemp.getMytreetype().equals("script")) {
				if (TreeTemp.getNodecontent() != null && TreeTemp.getNodecontent() != "") {
					String temptNodecontent = java.net.URLDecoder.decode(TreeTemp.getNodecontent(), "UTF-8");
					//替换大小于号
					temptNodecontent = temptNodecontent.replace("<", "&lt;");
					temptNodecontent = temptNodecontent.replace(">", "&gt;");
					temptNodecontent = temptNodecontent.replace("&lt;!--", "<!--");
					temptNodecontent = temptNodecontent.replace("--&gt;", "-->");
					TreeTemp.setNodecontent(temptNodecontent);
				}
				if (TreeTemp.getComment() != null && TreeTemp.getComment() != "") {
					String tempComment = java.net.URLDecoder.decode(TreeTemp.getComment(), "UTF-8");
					//替换大小于号
					tempComment = tempComment.replace("<", "&lt;");
					tempComment = tempComment.replace(">", "&gt;");
					tempComment = tempComment.replace("&lt;!--", "<!--");
					tempComment = tempComment.replace("--&gt;", "-->");
					TreeTemp.setComment(tempComment);
				}
				TreeTemp.setIcon("/res/css/zTreeStyle/img/diy/script.png");
			}
		}

		listTreeEntity.removeAll(createjobList);
		listTreeEntity.removeAll(updatejobList);
		listTreeEntity.removeAll(preList);
		listTreeEntity.removeAll(connList);

		//合并
		createjobList.addAll(updatejobList);
		createjobList.addAll(preList);
		createjobList.addAll(connList);
		createjobList.addAll(listTreeEntity);

		Gson gson = new Gson();
		String str = gson.toJson(createjobList);
		return str;
	}

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/GetTreeNodeInfoByIDAjax", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String GetTreeNodeInfoByIDAjax(int nodeid) {
		TreeEntity treeRoot = treeService.selectTreeById(nodeid);
		Gson gson = new Gson();
		String str = gson.toJson(treeRoot);
		return str;
	}

	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/GetSelDatabasesAjax", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String GetSelDatabasesAjax() {
		List<Database> databaseList = dataBaseService.selectAllDatabase();
		Gson gson = new Gson();
		String str = gson.toJson(databaseList);
		return str;
	}

	@Autowired
	private GenerateXmlService generateXmlService;
	
	@RequiresPermissions("ExtXml管理:查看xml作业")
	@RequestMapping(value = "/GetJobEtlXml", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String GetJobEtlXml(int nodeid) throws DocumentException, IOException, ParserConfigurationException, SAXException {
		return generateXmlService.GetJobEtlXml(nodeid);
	}

	@RequestMapping(value = "/SaveXMLAjax", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public String SaveXMLAjax(String nodeids, int jobid) {
		Gson gson = new Gson();
		try {
			List<TreeEntity> TreeEntityList = gson.fromJson(nodeids, new TypeToken<List<TreeEntity>>() {
			}.getType());
			if (TreeEntityList != null && TreeEntityList.size() > 0) {
				//删除当前任务下的节点
				int deleNum = treeService.deleteTreeByPid(jobid);

				//生成节点
				for (TreeEntity treeTemp : TreeEntityList) {
					treeService.insertTree(treeTemp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}

		return "1";
	}

	@RequestMapping(value = "/DeleNode", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String DeleNode(int nodeid) {
		int delenum = treeService.deleteTreeByIdAndPid(nodeid);
		return "";
	}

	@RequestMapping(value = "/UpdateNodeName", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String UpdateNodeName(int nodeid, String nodename) {
		TreeEntity treeEntity = new TreeEntity();
		treeEntity.setId(nodeid);
		treeEntity.setName(nodename);
		try {
			int delenum = treeService.UpdateNodeName(treeEntity);
		} catch (Exception e) {
			String test = "";
		}
		return "";
	}
}
